package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.UnLikesBehavior;
import com.heima.behavior.service.UnLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnLikesBehaviorServiceImpl implements UnLikesBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();//获取登陆的用户
        //判断参数
        if (dto == null ||user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建对象
        UnLikesBehavior unLikesBehavior = new UnLikesBehavior();
        unLikesBehavior.setArticleId(dto.getArticleId());//文章ID
        unLikesBehavior.setEquipmentId(dto.getEquipmentId());//设备ID
        unLikesBehavior.setUserId(user.getUserId());//用户ID
        unLikesBehavior.setCreatedTime(new Date());//创时间
        unLikesBehavior.setType(dto.getType());//操作类型:0 不喜欢  1 取消不喜欢
        if (dto.getType() == 0){
            mongoTemplate.save(unLikesBehavior);
        }else {
            //查询
            Query query = new Query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("userId").is(user.getUserId()));
            mongoTemplate.remove(query, UnLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
